<?php
namespace Modules\Queue\Controllers;

use Core\Mvc\Controller;
use Modules\Queue\Models\Queue as QueueModel;
use Core\Paginator\Adapter\Collection as CollectionPaginator;
use Modules\Queue\Library\Queue;

class AdminController extends Controller
{

    public function indexAction($page)
    {
        self::$variables += array(
            'title' => '队列',
            'description' => '任务列表',
            'params' => self::$variables['router_params'],
            'breadcrumb' => array(
                'admin' => array(
                    'href' => array(
                        'for' => 'adminIndex',
                    ),
                    'name' => '控制台',
                ),
                'queueList' => array(
                    'name' => '任务列表',
                ),
            ),
            'content' => array(),
        );

        $query = [
            'limit' => 30,
            'skip' => 30 * ($page - 1)
        ];
        $data = QueueModel::find($query);
        $dataPagination = new CollectionPaginator([
            'data' => $data,
            'query' => $query,
            'page' => $page,
            'collection' => '\Modules\Queue\Models\Queue'
        ]);
        $content['menuGroup'] = array(
            '#templates' => 'queueMenuGroup',
            'title' => '菜单',
            'data' => array(
                'runCron' => array(
                    'href' => array(
                        'for' => 'queue',
                        'id' => 0,
                    ),
                    'name' => '运行Cron'
                )
            ),
        );
        $content['queueList'] = array(
            '#templates' => array(
                'adminQueueList',
            ),
            'taskList' => $this->config->cache('task'),
            'data' => $dataPagination->getPaginate(),
        );
        self::$variables['content'] += $content;
    }

    public function deleteAction($id)
    {
        $queue = QueueModel::findById($id);
        if ($queue) {
            if ($queue->delete()) {
                $this->flashSession->success('删除成功');
            } else {
                $this->flashSession->error('删除失败');
            }
        } else {
            $this->flashSession->error('删除失败，数据不存在');
        }
        return $this->temMoved(array('for' => 'adminQueue', 'page' => 1));
    }

    public function resumedAction($id)
    {
        $queue = QueueModel::findById($id);
        if ($queue) {
            $queue->state = 0;
        }
        if ($queue->save()) {
            $this->flashSession->success('恢复成功');
        }else{
            $this->flashSession->error('恢复失败');
        }

        return $this->temMoved(array('for' => 'adminQueue', 'page' => 1));
    }
}
